package cn.iocoder.yudao.module.biz.service.bizsalesteam;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.biz.controller.admin.salesteam.vo.SanBizSalesTeamUser;
import cn.iocoder.yudao.module.biz.controller.admin.salesteam.vo.BizSalesTeamPageReqVO;
import cn.iocoder.yudao.module.biz.controller.admin.salesteam.vo.BizSalesTeamSaveReqVO;
import cn.iocoder.yudao.module.biz.dal.dataobject.bizsalesteam.BizSalesTeamDO;
import cn.iocoder.yudao.module.biz.dal.mysql.bizsalesteam.BizSalesTeamMapper;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.service.user.AdminUserServiceImpl;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import java.util.stream.Collectors;

import cn.iocoder.yudao.framework.common.util.object.BeanUtils;


import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.biz.enums.ErrorCodeConstants.BIZ_SALES_TEAM_NOT_EXISTS;

/**
 * 销售团队信息 Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
public class BizSalesTeamServiceImpl implements BizSalesTeamService {

    @Resource
    private AdminUserServiceImpl adminUserService;

    @Resource
    private BizSalesTeamMapper bizSalesTeamMapper;

    @Autowired
    private SanBizSalesTeamUserService sanBizSalesTeamUserService;

    @Override
    @Transactional
    public Long createBizSalesTeam(BizSalesTeamSaveReqVO createReqVO) {
        // 插入
        BizSalesTeamDO bizSalesTeam = BeanUtils.toBean(createReqVO, BizSalesTeamDO.class);
        bizSalesTeamMapper.insert(bizSalesTeam);
        QueryWrapper<SanBizSalesTeamUser> wrapper = new QueryWrapper<>();
        wrapper.eq("team_id", createReqVO.getTeamId());
        createReqVO.getItems().forEach(a -> {
            a.setTeamId(Long.valueOf(bizSalesTeam.getTeamId()));
        });
        sanBizSalesTeamUserService.remove(wrapper);
        // 清除用户所在的其他组，保证一个用户只存在一个组
        LambdaQueryWrapper<SanBizSalesTeamUser> lambdaWrapper = new LambdaQueryWrapper<>();
        lambdaWrapper.in(SanBizSalesTeamUser::getUserId,createReqVO.getItems().stream()
                .map(user -> String.valueOf(user.getUserId()))
                .collect(Collectors.toList()));
        sanBizSalesTeamUserService.remove(lambdaWrapper);

        sanBizSalesTeamUserService.saveBatch(createReqVO.getItems());
        // 返回
        return bizSalesTeam.getTeamId();
    }

    @Override
    @Transactional
    public void updateBizSalesTeam(BizSalesTeamSaveReqVO updateReqVO) {
        // 校验存在
        validateBizSalesTeamExists(updateReqVO.getTeamId());
        // 更新
        BizSalesTeamDO updateObj = BeanUtils.toBean(updateReqVO, BizSalesTeamDO.class);

        // 清除组内用户
        QueryWrapper<SanBizSalesTeamUser> wrapper = new QueryWrapper<>();
        wrapper.eq("team_id", updateReqVO.getTeamId());
        sanBizSalesTeamUserService.remove(wrapper);
        if(updateReqVO.getItems() != null && updateReqVO.getItems().size()>0){
            // 清除用户所在的其他组，保证一个用户只存在一个组
            LambdaQueryWrapper<SanBizSalesTeamUser> lambdaWrapper = new LambdaQueryWrapper<>();
            lambdaWrapper.in(SanBizSalesTeamUser::getUserId,updateReqVO.getItems().stream()
                    .map(user -> String.valueOf(user.getUserId()))
                    .collect(Collectors.toList()));
            sanBizSalesTeamUserService.remove(lambdaWrapper);

            updateReqVO.getItems().forEach(a -> {
                a.setTeamId(Long.valueOf(updateReqVO.getTeamId()));
            });
            sanBizSalesTeamUserService.saveBatch(updateReqVO.getItems());
        }

        bizSalesTeamMapper.updateById(updateObj);
    }

    @Override
    public void deleteBizSalesTeam(Integer id) {
        Map<String, Object> conditionMap = new HashMap<>();
        conditionMap.put("team_id", id);
        sanBizSalesTeamUserService.removeByMap(conditionMap);
        // 校验存在
        validateBizSalesTeamExists(id);
        // 删除
        bizSalesTeamMapper.deleteById(id);
    }

    @Override
        public void deleteBizSalesTeamListByIds(List<Integer> ids) {
        // 删除
        bizSalesTeamMapper.deleteByIds(ids);
        }


    private void validateBizSalesTeamExists(Integer id) {
        if (bizSalesTeamMapper.selectById(id) == null) {
            throw exception(BIZ_SALES_TEAM_NOT_EXISTS);
        }
    }

    @Override
    public BizSalesTeamDO getBizSalesTeam(Long id) {
        return bizSalesTeamMapper.selectById(id);
    }

    @Override
    public PageResult<BizSalesTeamDO> getBizSalesTeamPage(BizSalesTeamPageReqVO pageReqVO) {
        return bizSalesTeamMapper.selectPage(pageReqVO);
    }

    @Override
    public List<AdminUserDO> getUsers(Long teamId) {
        QueryWrapper<SanBizSalesTeamUser> a = new QueryWrapper<>();
        a.eq("team_id",teamId);
        List<SanBizSalesTeamUser> list = sanBizSalesTeamUserService.list(a);
        List<Long> longs = new ArrayList<>();
        list.forEach(aa ->{
            longs.add(aa.getUserId());
        });
        return adminUserService.getUserList(longs);
//        return listUser.getList();
    }

    @Override
    public List<AdminUserDO> getBizSalesTeamUser(Long id) {
        QueryWrapper<SanBizSalesTeamUser> a = new QueryWrapper<>();
        a.eq("user_id", id);
        List<SanBizSalesTeamUser> list = sanBizSalesTeamUserService.list(a);
        List<Long> longs = new ArrayList<>();
        list.forEach(aa -> {
            longs.add(aa.getUserId());
        });
        return adminUserService.getUserList(longs);
    }

}
